package com.study.manage.mvc.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.UserOrganizaRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.User;
import com.study.manage.domain.UserOrganiza;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.domain.enumm.UserType;
import com.study.manage.domain.enumm.VerifyState;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.SessionUser;
import com.study.manage.exception.ManageException;

@Controller
@RequestMapping("org")
public class OrgLoginController extends BaseController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserOrganizaRepository userOrganizaRepository;

    /**
     * 机构认证（登陆）
     * 
     */
    @RequestMapping(path = "login", method = RequestMethod.GET)
    public String org_login() {
        return "org/login";
    }

    /**
     * 退出（重新登陆）
     * 
     */
    @RequestMapping(path = "logout", method = RequestMethod.GET)
    public void org_logout() throws Exception {

        this.logout(request);
        response.sendRedirect(request.getContextPath() + "/org/login");
    }

    /**
     * 登陆验证
     * 
     */
    @ResponseBody
    @RequestMapping(path = "login-login", method = RequestMethod.POST)
    public AjaxResponse org_login(String userName, String password) {

        String retUrl = "/org/acc/authentication";
        AjaxResponse ajaxResponse = new AjaxResponse(true);
        User user = userRepository.findByPhone(userName);
        User orgUser = user;
        if (user == null || !user.hashPassword.equals(hashPassword(password, scret, user.salt))) {
            throw new ManageException("用户名或密码错误");
        }
        if (user.state == LiveDieState.DIE) {
            throw new ManageException("用户已删除");
        }
        SessionUser sessionUser = new SessionUser();
        sessionUser.setPhone(user.phone);
        // 校验是不是机构
        UserOrganiza organiza = userOrganizaRepository.findByRegUserId(user.id);
        if (organiza == null || organiza.state != VerifyState.LIVE) {
            if (user.type.getIndex() == 2) {
                retUrl = "/v2/index/index";
                // sessionUser.setIdentityFlg("1");
            } else {
                retUrl = "/org/acc/authentication";
            }
        } else {
            retUrl = "/v2/index/index";
            orgUser = userRepository.findOne(organiza.userId);
            // sessionUser.setfId(user.id);
            sessionUser.setUserOrganizaId(organiza.id);
        }
        sessionUser.setId(orgUser.id);
        sessionUser.setName(orgUser.name);
        sessionUser.setNumber(orgUser.number);
        sessionUser.setType(orgUser.type);
        sessionUser.setParentId(orgUser.parentId == null ? orgUser.id : orgUser.parentId);
        session.setAttribute("user", sessionUser);
        return ajaxResponse.setObj(retUrl);
    }

    @ResponseBody
    @RequestMapping(path = "login-code", method = RequestMethod.POST)
    public AjaxResponse org(String key) {

        AjaxResponse ajaxResponse = new AjaxResponse(true);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String userId = ops.get(key);
        String retUrl = "/org/acc/authentication";
        try {
            if (userId != null) {
                SessionUser su = new SessionUser();
                User u = userRepository.findOne(Long.valueOf(userId));
                if (u == null) {
                    return ajaxResponse.setMsg("扫描出错");
                }
                UserOrganiza organiza = null;
                if (u.type == UserType.ORG) {
                    organiza = userOrganizaRepository.findByUserId(u.id);
                } else {
                    organiza = userOrganizaRepository.findByRegUserId(u.id);
                }

                if (organiza != null && organiza.userId != null
                        && organiza.state != VerifyState.DIE) {
                    // su.setfId(u.id);
                    su.setUserOrganizaId(organiza.id);
                    u = userRepository.findOne(organiza.userId);
                    User regUser = userRepository.findOne(organiza.regUserId);
                    su.setPhone(regUser.phone);
                    retUrl = "/v2/index/index";
                }

                su.setId(u.id);
                su.setNumber(u.number);
                su.setType(u.type);
                su.setName(u.name);
                su.setParentId(u.parentId == null ? u.id : u.parentId);
                session.setAttribute("user", su);
            } else {
                ajaxResponse.setMsg("还未扫描");
            }
        } catch (Exception e) {
            logger.error("扫描出错", e);
            ajaxResponse.setMsg("还未扫描");
        }
        System.out.println(retUrl);
        return ajaxResponse.setObj(retUrl);
    }

    /*
     * @ResponseBody
     * 
     * @RequestMapping(path = "login-code", method = RequestMethod.POST) public AjaxResponse
     * check(String key, HttpServletRequest request) { AjaxResponse ajaxResponse = new
     * AjaxResponse(true); ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
     * String userId = ops.get(key); String retUrl = "/teach/renzheng"; if (userId != null) {
     * SessionUser su = new SessionUser(); User u = userRepository.findOne(Long.valueOf(userId)); if
     * (u == null) { return ajaxResponse.setMsg("扫描出错"); } if (u.type == UserType.ORG) { return
     * ajaxResponse.setMsg("还未扫描"); } su.setId(u.id); su.setNumber(u.number); su.setType(u.type);
     * su.setName(u.name); this.saveCurrentUser(request, su); } else { ajaxResponse.setMsg("还未扫描");
     * } return ajaxResponse.setObj(retUrl); }
     */

    @RequestMapping(path = "org", method = RequestMethod.GET)
    public String org() {
        return "org";
    }

}


